# -*- coding: utf-8 -*-
# filename: media.py
#! python3
from basic import Basic
import urllib
import requests
from urllib3 import encode_multipart_formdata
import json

class Media(object):
    def __init__(self):
        pass


    def post_files(self,accessToken,mediaType,fileName,filePath):
        # ttps://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
        postUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=%s&type=%s" % (accessToken, mediaType)
        data = {}
        header = {}
        data['file']= (fileName,open(filePath,'rb').read())
        
        encode_data = encode_multipart_formdata(data)
        
        data = encode_data[0]
        header['Content-Type'] = encode_data[1]
        r = requests.post(postUrl, headers=header, data=data)
        print(r.content)
    #下载临时图片
    def get(self, accessToken, mediaId):
        postUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s" % (accessToken, mediaId)
        urlResp = urllib.request.urlopen(postUrl)
        headers = urlResp.info()
        if ('Content-Type: application/json\r\n' in headers) or ('Content-Type: text/plain\r\n' in headers):
            jsonDict = json.loads(urlResp.read())
            print (jsonDict)
        else:
            buffer = urlResp.read()   #素材的二进制
            mediaFile = open("test_media.jpg", "wb")
            mediaFile.write(buffer)
            print ("get successful")


    #上传图文
    def add_news(self, accessToken, news):
        postUrl = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=%s" % accessToken
        urlResp = requests.post(postUrl, news)
        print (urlResp.content)

if __name__ == '__main__':
    myMedia = Media()
    accessToken = Basic().get_access_token()
    filePath = "./media/csl.jpg"   #请安实际填写
    fileName = 'csl.jpg'
    mediaType = "image"
    myMedia.post_files(accessToken,mediaType,fileName,filePath)
    # mediaId = '4sXv6U5tRx6wqRbLOZQWAEaYDkrwqF4p7V3DDXbDkFGJKozLpvW85h1o_0NjqJPH'
    # myMedia.get(accessToken,mediaId)
    
    # news =(
    # {
    #     "articles":
    #     [
    #         {
    #         "title": "test",
    #         "thumb_media_id": "4sXv6U5tRx6wqRbLOZQWAEaYDkrwqF4p7V3DDXbDkFGJKozLpvW85h1o_0NjqJPH",
    #         "author": "vickey",
    #         "digest": "",
    #         "show_cover_pic": 1,
    #         "content": '''<p><img src="" alt="" data-width="null" data-ratio="NaN"><br  /><img src="" alt="" data-width="null" data-ratio="NaN"><br  /></p>''',
    #         "content_source_url": "",
    #         }
    #     ]
    # })
    # news = json.dumps(news, ensure_ascii=False)
    # myMedia.add_news(accessToken, news)